# -*- coding: utf-8 -*-
import asyncio
import sys
from sanic import Sanic
from sanic import response
import time
import random
from env_init.environment import *
import Config
from Agent.MainAgent5  import *

app = Sanic(__name__)

def LoctionToMyEnv(x,y):
	return x * Config.CHECKERBOARDSIZE + y



@app.route('/start',methods=["POST"])
async def on_start(request):
	json = request.json
	print (json)
	#重置步数
	Maintrategy.Runnum = 0
	return response.json({})

@app.route('/step',methods=["POST"])
async def on_step(request):


	json = request.json
	player1 = json["player1"]
	player2 = json["player2"]


	if player1["name"] == "mingong5":
		player = 1

	if player2["name"] == "mingong5":
		player = 2

	play1state = LoctionToMyEnv(int(player1["x"]),int(player1["y"]))
	play2state = LoctionToMyEnv(int(player2["x"]),int(player2["y"]))

	play1score = float(player1["value"])
	play2score = float(player2["value"])

	play1jobs  = float(player1["n_jobs"])
	play2jobs =  float(player2["n_jobs"])

	final1Score = float(player1["score"])
	final2Score = float(player2["score"])

	play1base = LoctionToMyEnv(int(player1["home_x"]),int(player1["home_y"]))
	play2base = LoctionToMyEnv(int(player2["home_x"]),int(player2["home_y"]))


	barrier_states = set()
	walls = json["walls"]
	for oneDic in walls:
		barrier = LoctionToMyEnv(int(oneDic["x"]),int(oneDic["y"]))
		barrier_states.add(barrier)

	#给出取值向量
	reward_states = {}
	jobs = json["jobs"]
	for oneDic in jobs:
		reward_location = LoctionToMyEnv(int(oneDic["x"]),int(oneDic["y"]))
		reward_states[reward_location] = float(oneDic["value"])


	#给出当前环境的ENV
	env = deliveryManEnv(barrier_states=barrier_states,reward_states=reward_states,
						 play1state = play1state,play2state = play2state,
						 play1score = play1score,play2score = play2score,
						 final1Score = final1Score,final2Score = final2Score,
						 play1jobs = play1jobs,play2jobs = play2jobs,
						 play1base = play1base,play2base = play2base)

	#给出当前棋局走棋
	mainAgent = Maintrategy(env, player=player)
	action = mainAgent.getAction()


	# await asyncio.sleep(3)
	print (json)
	return response.json({'action':action})

@app.route('/end',methods=["POST"])
async def on_end(request):
	json = request.json
	print (json)
	Maintrategy.Runnum = 0
	return response.json({})

def main():
	seed = int(sys.argv[1])
	random.seed(seed)
	app.run(host='0.0.0.0', port=8889)

if __name__ == '__main__':
	main()


